﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kugar.Core.ExtMethod;
using Kugar.Core.Web;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json.Linq;

namespace Kugar.UI.Web.AdminLTE.Helpers
{
    public static class RequestExtMethod
    {
        /// <summary>
        /// 获取html中使用CityPicker控件产生的数据
        /// </summary>
        /// <param name="request"></param>
        /// <param name="preName"></param>
        /// <returns></returns>
        public static (string title, string proviceCode, string cityCode, string districtCode) GetCityPicker(
            this HttpRequest request, string preName)
        {
            return (request.GetString(preName), request.GetString(preName + "_ProvinceCode"),
                request.GetString(preName + "_CityCode"), request.GetString(preName + "_DistrictCode"));
        }

        public static (string title, string url, string mime)[] GetFileInfos(this HttpRequest request, string name)
        {
            var v = request.GetString($"{name}__fileinfo");

            try
            {
                var jsonArray = JArray.Parse(v);

                return jsonArray.Select(x =>
                {
                    var json = (JObject) x;
                    
                    return (json.GetString("Title"), json.GetString("FileUrl"), json.GetString("Mime"));
                }).ToArrayEx();
            }
            catch (Exception e)
            {
                return Array.Empty<(string title, string url, string mime)>();
            }
        }
    }
}
